package com.leo.userprovider.controller

import com.leo.orderbase.po.User
import com.leo.userprovider.responity.UserResponity
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.ModelAndView


@RestController
class UserController {

    @Autowired
    lateinit var userResponity: UserResponity

    @CrossOrigin
    @ResponseBody
    @GetMapping("getAllUser")
    fun getAllUser(): String {
        val all = userResponity.findAll()
        var names = ""
        all?.forEach {
            if (names != "") {
                names += ","
            }
            names += (it.name)
        }
        return names
    }

    @GetMapping("saveUser/{name}")
    @ResponseBody
    fun saveUser(@PathVariable("name") name: String): User {
        val user = userResponity.findUserByName(name)
        if (user == null) {
            val save = User(name)
            return userResponity.save(save)
        }
        return user
    }

    @ResponseBody
    @GetMapping("deleteUsers/{names}")
    fun deleteUser(@PathVariable("names") names: String) {
        val split = names.split(",")
        split.forEach { name ->
            val user = userResponity.findUserByName(name)
            user?.let {
                userResponity.delete(it)
            }
        }
    }

    @RequestMapping("index")
    @ResponseBody
    fun index(): ModelAndView {
        val view = ModelAndView("index")
        view.addObject("users", getAllUser())
        return view
    }

    @RequestMapping("/freemarker")
    fun freemarker(map: MutableMap<String, Any>): String {
        map["name"] = "Joe"
        map["sex"] = 1    //sex:性别，1：男；0：女；

        // 模拟数据
        val friends = ArrayList<Map<String, Any>>()
        var friend: MutableMap<String, Any> = HashMap()
        friend["name"] = "xbq"
        friend["age"] = 22
        friends.add(friend)
        friend = HashMap()
        friend["name"] = "July"
        friend["age"] = 18
        friends.add(friend)
        map["friends"] = friends
        return "test"
    }
}